<template>
    <div style="margin-bottom: 24px;">
        <TitleTips title="变更设计内容"></TitleTips>
        <el-form>
            <el-form-item label="变更设计内容" prop="detailList" required>
                <BaseButton plain @click="handleSelectProject">选择清单子目</BaseButton>
            </el-form-item>
        </el-form>
        <BaseTable :columns="columns" :data="tableList">
            <template #header="{ scope: { column } }">
                <span> <i class="required-start">*</i> {{ column.label }} </span>
            </template>

            <template #changeType="{ scope: { row } }">
                <el-radio-group v-model="row.changeType">
                    <el-radio :label="1">增加</el-radio>
                    <el-radio :label="2">减少</el-radio>
                </el-radio-group>
            </template>
            <template #changeQuantity="{ scope: { row, $index } }">
                <el-input v-model.trim="row.changeQuantity" type="number" clearable :placeholder="row.quantityPlaceholder" @blur="handleValidateQuyantityOne(row, $index)" />
            </template>
            <template #changeAmount="{ scope: { row } }">
                <span :class="row.changeType === 1 ? 'color-blue' : 'color-red'">{{ computeTotal(row) }}</span>
            </template>
            <template #handle="{ scope: { $index } }">
                <BaseButton type="text" color="danger" @click="handleDelete($index)">移除</BaseButton>
            </template>
        </BaseTable>
        <div class="table-footer">
            合计： 增加金额：<span class="color-blue" style="margin-right: 16px;">￥{{ total.incremental }}</span>
            减少金额：<span class="color-red">￥{{ total.reductive }}</span>
        </div>

        <ProjectListDialog :id="id" ref="projectListDialog" @success="getTableList"></ProjectListDialog>
    </div>
</template>

<script>
import reconfirm from '@/utils/reconfirm'
import ProjectListDialog from './ProjectListDialog'

import { isNumber2 } from '@/utils/validate'
import BigNumber from 'bignumber.js'

export default {
    name: 'InventoryTable',
    components: {
        ProjectListDialog,
    },
    props: {
        id: {
            type: [Number, String],
            default: '' // 合同id
        },
    },
    data() {
        return {
            tableList: [],
            columns: Object.freeze([
                {
                    attrs: {
                        prop: 'number',
                        label: '序号',
                        width: '70',
                        type: 'index'
                    }
                },
                {
                    attrs: {
                        prop: 'listSubitemCode',
                        label: '清单子目编码',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'listSubitemName',
                        label: '清单子目名称',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'unitSymbol',
                        label: '单位',
                        width: '80',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'quantity',
                        label: '原设计数量',
                        width: '110',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'currentQuantity',
                        label: '当前数量',
                        width: '110',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'price',
                        label: '单价（元）',
                        width: '120',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'changeType',
                    headerSlot: 'header',
                    attrs: {
                        prop: 'changeType',
                        label: '变更类型',
                        width: '170'
                    }
                },
                {
                    slot: 'changeQuantity',
                    headerSlot: 'header',
                    attrs: {
                        prop: 'changeQuantity',
                        label: '变更数量',
                        width: '256',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'changeAmount',
                    attrs: {
                        prop: 'changeAmount',
                        label: '变更金额（元）',
                        width: '170',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        width: '140',
                        fixed: 'right'
                    }
                }
            ])
        }
    },
    computed: {
        total() {
            const total = {incremental: 0.00, reductive: 0.00}
            this.tableList.forEach(item => {
                if (item.changeType === 1) {
                    total.incremental = new BigNumber(item.changeAmount || 0).plus(total.incremental)
                }
                if (item.changeType === 2) {
                    total.reductive = new BigNumber(item.changeAmount || 0).plus(total.reductive)
                }
            })
            total.incremental = total.incremental.toFixed(2)
            total.reductive = total.reductive.toFixed(2)
            return total
        }
    },
    methods: {
        computeTotal(row) {
            if (!row.changeQuantity && row.changeQuantity !== 0) {
                return ''
            }
            row.changeAmount = new BigNumber(row.changeQuantity || 0).times(row.price).toFixed(2)
            return row.changeAmount
        },
        getTableList(data) {
            console.log('data>>>', data)
            const list = data.map(item => {
                let quantityPlaceholder = ''
                if (item.decimalPlace === 0) {
                    quantityPlaceholder = '请输入数量，保留整数'
                } else {
                    quantityPlaceholder = `请输入数量，可保留${item.decimalPlace}位小数`
                }
                return {
                    ...item,
                    quantityPlaceholder
                }
            })
            this.tableList.push(...list)
        },
        handleSelectProject() {
            const ids = this.tableList.map((item) => item.id)
            this.$refs['projectListDialog'].open(ids)
        },
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                text: '是否删除当前数据',
                callback: () => {
                    this.tableList.splice(index, 1)
                }
            })
        },
        validate() {
            if (!this.validateChangeType()) {
                return false
            }
            if (!this.validateQuantities()) {
                return false
            }
            return true
        },

        validQuantity(value, decimalPlace) {
            const regex = this.createDecimalRegex(decimalPlace)
            if (!regex.test(value)) {
                return false
            } else {
                return true
            }
        },
        createDecimalRegex(places) {
            if (places === 0) {
                return /^\d+$/
            }
            // 生成对应位数小数的正则表达式字符串
            const decimalPart = `(?:\\.(\\d{1,${places}}))?`
            const regexStr = `^\\d+${decimalPart}$`            
            return new RegExp(regexStr)
        },

        validateQuantities() {
            let isValid = true
            for (let i = 0; i < this.tableList.length && isValid; i++) {
                const item = this.tableList[i]
                if (!item.changeQuantity) {
                    this.$message.error(`变更数量(序号${i + 1})不能为空！`)
                    isValid = false
                    break // 验证未通过，跳出内层循环
                } else if (!this.validQuantity(Number(item.changeQuantity), item.decimalPlace)) {
                    this.$message.error(`变更数量(序号${i + 1})格式错误！`)
                    isValid = false
                    break // 验证未通过，跳出内层循环
                } else if (item.changeType === 2 && Number(item.changeQuantity) > Number(item.currentQuantity)) {
                    this.$message.error(`变更数量(序号${i + 1})不能大于当前数量！`)
                    isValid = false
                    break
                }
            }
            return isValid
        },
        handleValidateQuyantityOne(row, i) {
            if (!row.changeQuantity) {
                return
            } else if (!this.validQuantity(Number(row.changeQuantity), row.decimalPlace)) {
                this.$message.error(`变更数量(序号${i + 1})格式错误！`) 
            } else if (row.changeType === 2 && Number(row.changeQuantity) > Number(row.currentQuantity)) {
                this.$message.error(`变更数量(序号${i + 1})不能大于当前数量！`)
            }
        },
        validateChangeType() {
            let isValid = true
            for (let i = 0; i < this.tableList.length && isValid; i++) {
                const item = this.tableList[i]
                if (!item.changeType) {
                    this.$message.error(`请选择变更类型(序号${i + 1})！`)
                    isValid = false
                    break // 验证未通过，跳出内层循环
                }
            }
            return isValid
        },
    }
}
</script>

<style lang="scss" scoped>
.required-start {
    color: #e50834;
    margin-right: 4px;
    font-style: normal;
}
.table-footer {
    background-color: #f6f6f6;
    padding: 8px 20px;
    text-align: right;
    font-size: 14px;
    margin-bottom: 24px;
}
</style>
